<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="选择接收人" width="1000px" @ok="handleSubmit">
    <BasicTable @register="registerTable" :rowSelection="rowSelection" style="padding: 5px">
      <template #form-addUser="{ model, field }">
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleCreate"> 新增</a-button>
      </template>
    </BasicTable>
  </BasicModal>
  <ReceiverDrawer @register="registerDrawer" @success="reload" />
</template>
<script lang="ts" setup>
  import { ref, unref, toRaw, reactive, computed } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { BasicTable, useTable } from "/@/components/Table"
  import { columns, searchFormSchema } from "../receiver.data"
  import ReceiverDrawer from "./ReceiverDrawer.vue"
  import { useDrawer } from "/@/components/Drawer"
  import { pageReceiver } from "../receiver.api"
  import { map } from "lodash"

  // 声明Emits
  const emit = defineEmits(["select", "register"])
  const checkedKeys = ref<Array<string | number>>([])

  // 注册drawer
  const [registerDrawer, { openDrawer }] = useDrawer()

  //注册table数据
  const [registerTable, { reload, getSelectRows }] = useTable({
    api: pageReceiver,
    rowKey: "id",
    columns: columns,
    formConfig: {
      labelWidth: 60,
      schemas: searchFormSchema,
      baseRowStyle: { maxHeight: "20px", marginBottom: "20px" },
      autoSubmitOnEnter: true,
      showActionButtonGroup: false,
    },
    striped: true,
    useSearchForm: true,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    canResize: false,
  })

  /**
   * 选择列配置
   */
  const rowSelection = {
    type: "checkbox", // 为 radio 是单选
    columnWidth: 50,
    selectedRowKeys: checkedKeys,
    onChange: onSelectChange,
  }

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {})

  /**
   * 选择事件
   */
  function onSelectChange(selectedRowKeys: (string | number)[]) {
    checkedKeys.value = selectedRowKeys
  }

  const handleCreate = () => {
    openDrawer(true, {
      isUpdate: false,
      showFooter: true,
    })
  }

  //提交事件
  async function handleSubmit() {
    const selectRows = await getSelectRows().filter((e) => checkedKeys.value.includes(e.id))
    setModalProps({ confirmLoading: true })
    //关闭弹窗
    closeModal()
    //刷新列表
    emit("select", toRaw(unref(selectRows.map((e) => e.id))))
    setModalProps({ confirmLoading: false })
  }
</script>
